// @author Tjzlo
// @version 2025/2/17 01:54

package com.old.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.old.dto.ActivityDTO;
import com.old.dto.ActivityQueryDTO;
import com.old.dto.ActivityUpdateDTO;
import com.old.entity.Activity;
import com.old.mapper.ActivityMapper;
import com.old.mapper.UserMapper;
import com.old.result.PageBean;
import com.old.result.Result;
import com.old.service.ActivityService;
import com.old.service.UserService;
import com.old.util.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ActivityServiceImpl implements ActivityService {

    private final ActivityMapper activityMapper;

    private final ObjectMapper objectMapper;
    private final UserMapper userMapper ;

    /**
     * 添加活动信息
     *
     * @param activityDTO
     */
    @Override
    @Transactional
    public void addActivity(ActivityDTO activityDTO) {
//        User user = userMapper.findByID(activityDTO.getAuthorId());
//        activityDTO.setName(user.getName());
        //TODO 预留接口从多表查询获取name值和活动id设置为uuid
//        long UUID = System.currentTimeMillis();
//        activityDTO.setActivityId((int) UUID);
        //覆盖前端传入 强制为审核态
        activityDTO.setIsShow(1);
        //通过用户id获取头像
        String avatar = userMapper.getUserAvatar(activityDTO.getAuthorId());
        if(avatar == null){
            //无法从sql获取头像时,使用默认头像
            avatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
        }
        activityDTO.setAvatar(avatar);
        activityDTO.setJoinNum("[]");
//        Map<String, Object> map = ThreadLocalUtil.get();
//        String avatar = (String) map.get("avatar");

        activityMapper.addActivity(activityDTO);
    }

    /**
     * 获取活动列表
     *
     * @param activityQueryDTO
     * @return
     */
    @Override
    public PageBean activityListPage(ActivityQueryDTO activityQueryDTO) {
        PageHelper.startPage(activityQueryDTO.getPageNo(), activityQueryDTO.getPageSize());
        Page<Activity> page = activityMapper.activityListPage(activityQueryDTO);

        long total = page.getTotal();
        List<Activity> records = page.getResult();
        LocalDateTime now = LocalDateTime.now();
        for (Activity activity : records) {
            if ( now.isAfter(activity.getEndTime())) {
                ActivityDTO activityDTO = new ActivityDTO();
                activityDTO.setActivityId(activity.getActivityId());
                activityDTO.setIsShow(0);
                activityMapper.updateActivity(activityDTO);
                activity.setIsShow(0);
            } else {
                activity.setIsShow(1);
            }
        }

        return new PageBean(total, records);
    }

    /**
     * 取消报名活动
     *
     * @param activityId
     */
    @Override
    @Transactional
    public Result<String> cancelSignUp(Integer activityId, Integer userId) {
        try {
            // 1. 校验活动是否存在
            ActivityDTO activity = activityMapper.findActivityById(activityId);
            if (activity == null) {
                return Result.error("活动不存在");
            }

            // 2. 解析当前报名用户列表
            List<Integer> joinList = parseJoinNum(activity.getJoinNum());

            // 3. 检查用户是否已报名
            if (!joinList.contains(userId)) {
                return Result.error("用户未报名该活动");
            }

            // 4. 移除用户并更新
            joinList.remove(userId);
            String newJoinNum = objectMapper.writeValueAsString(joinList);
            activityMapper.updateJoinNum(activityId, newJoinNum);

            return Result.success("取消报名成功");
        } catch (JsonProcessingException e) {
            System.out.println("JSON解析异常" + e);
            return Result.error("数据处理失败");
        }
    }

    // 解析JSON数组字符串
    private List<Integer> parseJoinNum(String joinNum) throws JsonProcessingException {
        if (joinNum == null || joinNum.trim().isEmpty()) {
            return new ArrayList<>();
        }
        return objectMapper.readValue(joinNum, new TypeReference<List<Integer>>() {
        });
    }

    /**
     * 报名活动
     *
     * @param activityId
     */
    @Override
    @Transactional
    public Result<String> joinActivity(Integer activityId, Integer userId) {
        try {
            ActivityDTO activity = activityMapper.findActivityById(activityId);
            if (activity == null) {
                return Result.error("活动不存在");
            }

            List<Integer> joinList = parseJoinNum(activity.getJoinNum());

            // 检查是否重复报名
            if (joinList.contains(userId)) {
                return Result.error("请勿重复报名");
            }

            joinList.add(userId);
            String newJoinNum = objectMapper.writeValueAsString(joinList);
            activityMapper.updateJoinNum(activityId, newJoinNum);

            return Result.success("报名成功");
        } catch (JsonProcessingException e) {
            System.out.println("JSON处理异常" + e);
            return Result.error("数据处理失败");
        }
    }

    /**
     * 修改用户活动
     *
     * @param activityUpdateDTO
     */

    @Override
    @Transactional
    public void updateActivityInfo(ActivityUpdateDTO activityUpdateDTO) {
        // 1. 查询活动是否存在
        ActivityDTO activity = activityMapper.findActivityById(activityUpdateDTO.getActivityId());
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }

        // 2. 检查当前用户是否有权限修改活动
//        if (!activity.getAuthorId().equals(userId)) {
//            throw new RuntimeException("无权修改该活动");
//        }

        // 3. 更新活动信息
        activity.setImageUrl(activityUpdateDTO.getImageUrl());
        activity.setTitle(activityUpdateDTO.getTitle());
        activity.setContent(activityUpdateDTO.getContent());
        activity.setStartTime(activityUpdateDTO.getStartTime());
        activity.setEndTime(activityUpdateDTO.getEndTime());
        activity.setIsShow(activityUpdateDTO.getIsShow());
        activity.setActivityNum(activityUpdateDTO.getActivityNum());
        activity.setActivityPlace(activityUpdateDTO.getActivityPlace());
        activity.setUpdateTime(LocalDateTime.now());

        // 4. 保存到数据库
        activityMapper.updateActivity(activity);
    }

    /**
     * 删除用户活动
     *
     * @param activityId
     */

    @Override
    @Transactional
    public void deleteActivity(Integer activityId) {
        // 1. 查询活动是否存在
        ActivityDTO activity = activityMapper.findActivityById(activityId);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }

        // 2. 检查当前用户是否有权限删除活动
//        if (!activity.getAuthorId().equals(userId)) {
//            throw new RuntimeException("无权删除该活动");
//        }

        // 3. 删除活动
        activityMapper.deleteActivity(activityId);
    }

    @Override
    public PageBean pageList(Integer pageNo, Integer pageSize, Integer sortBy, String searchTerms, Integer userId) throws JsonProcessingException {
        PageHelper.startPage(pageNo, pageSize);

//        Map<String, Object> map = ThreadLocalUtil.get();
//        Integer userId = (Integer) map.get("id");
        List<Activity> list = activityMapper.list(sortBy, searchTerms);
        Page<Activity> p = (Page<Activity>) list;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        List list_init = pageBean.getList();
        for (Object o : list_init) {
            Activity activity = (Activity) o;
            // 解析参与人数
            ObjectMapper objectMapper = new ObjectMapper();
            LocalDateTime now = LocalDateTime.now();
            if ( now.isAfter(activity.getEndTime())) {
                ActivityDTO activityDTO = new ActivityDTO();
                activityDTO.setActivityId(activity.getActivityId());
                activityDTO.setIsShow(0);
                activityMapper.updateActivity(activityDTO);
                activity.setIsShow(0);
            } else {
                activity.setIsShow(1);
            }
            // 解析为JsonNode对象
            if (activity.getJoinNum() != null) {
                JsonNode jsonNode = objectMapper.readTree(activity.getJoinNum());
                // 获取数组元素个数
                int elementCount = jsonNode.size();

                if (activity.getJoinNum() != null) {
                    if (userId != null) {
                        // 将字符串转换为JSONArray
                        JSONArray jsonArray = JSON.parseArray(activity.getJoinNum());
                        // 使用FastJSON内置方法检查元素是否存在
                        boolean isGood = jsonArray.contains(userId);
                        if (isGood){
                            // 设置帖子的状态
                            activity.setIsjoin(1);
                        }
                    } else {
                        activity.setIsjoin(0);
                    }
                }
                activity.setJoinNum(Integer.toString(elementCount));

            }
        }
        return pageBean;
    }

    //用户参加的活动列表
    @Override
    public PageBean userJoinActivityListPage(ActivityQueryDTO activityQueryDTO) {

        PageHelper.startPage(activityQueryDTO.getPageNo(), activityQueryDTO.getPageSize());
        Page<Activity> page = activityMapper.userJoinActivityListPage(activityQueryDTO);

//        long total = page.getTotal();
        List<Activity> records = page.getResult();
        //records列表中移除那些joinNum字段（转换为JSONArray后）不包含特定authorId的记录
        records = records.stream()
                .filter(record -> {
                    JSONArray jsonArray = JSON.parseArray(record.getJoinNum());
                    return jsonArray.contains(activityQueryDTO.getAuthorId());
                })
                .collect(Collectors.toList());
        LocalDateTime now = LocalDateTime.now();
        for (Activity activity : records) {
            if ( now.isAfter(activity.getEndTime())) {
                ActivityDTO activityDTO = new ActivityDTO();
                activityDTO.setActivityId(activity.getActivityId());
                activityDTO.setIsShow(0);
                activityMapper.updateActivity(activityDTO);
                activity.setIsShow(0);
            } else {
                activity.setIsShow(1);
            }
        }

//        for (Activity record : records) {
//            // 将字符串转换为JSONArray
//            JSONArray jsonArray = JSON.parseArray(record.getJoinNum());
//            // 使用FastJSON内置方法检查元素是否存在
//            boolean isJoin = jsonArray.contains(activityQueryDTO.getAuthorId());
//            if (!isJoin){
//                records.remove(record);
//            }
//        }
        //recodes的长度
        long total = records.size();
        return new PageBean(total, records);
    }

    //批量删除活动
    @Override
    @Transactional
    public void deleteActivitiesByIds(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) return;
        activityMapper.batchDeleteByIds(ids);
    }
}
